#include "StdAfx.h"
#include "ObstacleMap.h"
#include "colors.h"
#include <ctime>
#include <iostream>

const float ObstacleMap::OBSTACLE_DEFAULT_LEN_X = 8.0f;
const float ObstacleMap::OBSTACLE_DEFAULT_LEN_Y = 8.0f;
const float ObstacleMap::OBSTACLE_DEFAULT_LEN_Z = 8.0f;

ObstacleMap::ObstacleMap(void)
{
}

ObstacleMap::~ObstacleMap(void)
{
	// since we're using pointers, we need to manually delete each item within the vector
	if (blocks.size() > 0)
	{
		for(std::vector<Block*>::iterator it = blocks.begin(); it != blocks.end(); ++it) 
			delete (*it);
	}
}

void ObstacleMap::init(int startX, int startY, int endX, int endY)
{
	boundingBox.left = startX;
	boundingBox.top = startY;
	boundingBox.right = endX;
	boundingBox.bottom = endY;
	//RandomizeObstacleMap(); // recieve obstacle locations from the server
}

// add an obstacle to our map
void ObstacleMap::AddObstacle(BlockType type, int x, int z)
{
	// no need to check for collisions between blocks as the server would handle it
	Block* b = new Block(x, 0.0f, z,
		OBSTACLE_DEFAULT_LEN_X, OBSTACLE_DEFAULT_LEN_Y, OBSTACLE_DEFAULT_LEN_Z);
	b->setType(type);
	blocks.push_back(b);
}

void ObstacleMap::RandomizeObstacleMap()
{
	srand(time(0));
	int num = rand() % OBSTACLE_DEFAULT_MAX_NUMBER;
	if (num < OBSTACLE_DEFAULT_MIN_NUMBER) num = OBSTACLE_DEFAULT_MIN_NUMBER;

	int goalNum = rand() % num; // the goal number can be any number under the number of blocks
	int maxWidth = (boundingBox.right - boundingBox.left - OBSTACLE_DEFAULT_LEN_X)/2;
	int maxHeight = (boundingBox.bottom - boundingBox.top - OBSTACLE_DEFAULT_LEN_Z)/2;
	for (int i = 0; i < num; i++)
	{
		int x = rand() % maxWidth;
		int z = rand() % maxHeight;

		Block* b = new Block(x, 0.0f, z,
			OBSTACLE_DEFAULT_LEN_X, OBSTACLE_DEFAULT_LEN_Y, OBSTACLE_DEFAULT_LEN_Z);				

		if (goalNum == i)
		{
			b->setType(BLOCK_GOAL);
		}
		blocks.push_back(b);
	
		char* buf = new char[512];
		sprintf(buf, "block @ (%.4g, %.4g, %.4g)\n", b->m_Pos.x, b->m_Pos.y, b->m_Pos.z);
		OutputDebugString(buf);
		delete[] buf;
	}
}

void ObstacleMap::render(long time)
{
	for(std::vector<Block*>::iterator it = blocks.begin(); it != blocks.end(); ++it)
		(*it)->render(time);
}

Block *ObstacleMap::collides(D3DXVECTOR3 pt)
{

	for(std::vector<Block*>::iterator it = blocks.begin(); it != blocks.end(); ++it)
	{
		if ((*it)->collidespoint(pt))
		{
			return (*it);
		}
	}
	return NULL;
}
